<!-- 分页 -->
<template>
  <div :class="{'hidden':hidden}" class="py-8 bg-white flex justify-end">
    <el-pagination :background="background" :current-page.sync="currentPage" :page-size.sync="pageSize" :layout="layout" :page-sizes="pageSizes" :total="total" v-bind="$attrs" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
</template>

<script>
import { scrollTo } from '@/utils/scroll-to'
import { computed } from '@vue/composition-api'

// 双向数据绑定页数条数修改
function update({ page, limit }, emit) {
  const currentPage = computed({
    get() {
      return page
    },
    set(val) {
      emit('update:page', val)
    }
  })

  const pageSize = computed({
    get() {
      return limit
    },
    set(val) {
      emit('update:limit', val)
    }
  })

  return {
    currentPage,
    pageSize
  }
}

// 事件处理
function handle({ currentPage, pageSize, autoScroll }, emit) {
  function handleSizeChange(val) {
    emit('pagination', { page: currentPage, limit: val })
    if (autoScroll) {
      scrollTo(0, 800)
    }
  }
  function handleCurrentChange(val) {
    emit('pagination', { page: val, limit: pageSize })
    if (autoScroll) {
      scrollTo(0, 800)
    }
  }

  return {
    handleSizeChange,
    handleCurrentChange
  }
}

export default {
  name: 'Pagination',
  props: {
    total: {
      required: true,
      type: Number
    },
    page: {
      type: Number,
      default: 1
    },
    limit: {
      type: Number,
      default: 20
    },
    pageSizes: {
      type: Array,
      default() {
        return [10, 20, 30, 50]
      }
    },
    layout: {
      type: String,
      default: 'total, sizes, prev, pager, next, jumper'
    },
    background: {
      type: Boolean,
      default: true
    },
    autoScroll: {
      type: Boolean,
      default: true
    },
    hidden: {
      type: Boolean,
      default: false
    }
  },
  setup(props, { emit }) {
    return {
      ...update(props, emit),
      ...handle(props, emit)
    }
  },
}
</script>

<style scoped>
.hidden {
  display: none;
}
</style>
